package org.ishequ.smslistener;

import org.ishequ.domain.MessageItem;
import org.ishequ.domain.SMS;
import android.content.ContentResolver;
import android.database.ContentObserver;
import android.database.Cursor;
import android.os.Handler;
import android.os.Message;
import android.util.Log;

public class SMSObserver extends ContentObserver {

	private static final String TAG = "SMSObserver";
	
	private ContentResolver mResolver;
	private Handler mHandler;

	private static final String[] PROJECTION = new String[]{
		SMS._ID,// 0
		SMS.TYPE,// 1
		SMS.ADDRESS,// 2
		SMS.BODY,// 3
		SMS.DATE,// 4
		SMS.THREAD_ID,// 5
		SMS.READ,// 6
		SMS.PROTOCOL // 7
	};
	
	private static final String SORT_ORDER = "_id desc limit 1";

	private static final int COLUMN_INDEX_ID    = 0;
    private static final int COLUMN_INDEX_TYPE  = 1;
    private static final int COLUMN_INDEX_PHONE = 2;
    private static final int COLUMN_INDEX_BODY  = 3;
    private static final int COLUMN_INDEX_PROTOCOL = 7;
    
    private static final int SMS_SEND = 1;
	
	public SMSObserver(ContentResolver resolver, Handler handler) {
		super(handler);
		this.mHandler = handler;
		this.mResolver = resolver;
	}

	@Override
	public void onChange(boolean selfChange) {
		//监听发送短信
		Cursor cursor = mResolver.query(SMS.CONTNET_URI_OUTBOX, PROJECTION, 
							null,null, SORT_ORDER);
		
		int id, type, protocol;
        String phone, body;
        Message message;
        MessageItem item = null;
        
		if(cursor.moveToNext()){
			id = cursor.getInt(COLUMN_INDEX_ID);
			type = cursor.getInt(COLUMN_INDEX_TYPE);
			protocol = cursor.getInt(COLUMN_INDEX_PROTOCOL);
			phone = cursor.getString(COLUMN_INDEX_PHONE);
			body = cursor.getString(COLUMN_INDEX_BODY);
			
			item = new MessageItem();
			item.setBody(body);
			item.setId(id);
			item.setPhone(phone);
			item.setProtocol(protocol);
			item.setType(type);
			
			message = new Message();
			message.obj = item;
			message.what = SMS_SEND;
			mHandler.sendMessage(message);
			
			Log.i(TAG, "onChange cursor->"+ item);
		}
	
	}

}
